package cn.fl.product.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.product.service.ISplInfoService;
import cn.fl.product.service.ISplUsrRService;
import cn.fl.product.vo.SplInfoVO;
import cn.fl.product.vo.SplUsrRVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.spl.facade.framework.constant.DictionaryConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.BasisDataRelDescEnum;
import fl.spl.facade.spl.api.ISplCommBlackListApiService;
import fl.spl.facade.spl.condition.SplCommBlackListQC;
import fl.spl.facade.spl.condition.SplUsrRQC;
import fl.spl.facade.spl.constant.SplBscInfoApplyConstant;
import fl.spl.facade.spl.constant.SplCommBlackListConstant;
import fl.spl.facade.spl.dto.SplCommBlackListDTO;
import fl.spl.facade.store.api.ISplPropInfoApiService;
import fl.spl.facade.store.condition.SplPropInfoQueryCondition;
import fl.spl.facade.store.dto.SplPropInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 供应商-系统用户关系表 控制层
 */
@Controller
@RequestMapping("/product/splUsrR")
public class SplUsrRController extends BaseController {

	/**
	 * SplUsrR 服务层BEAN
	 */
	@Autowired
	private ISplUsrRService splUsrRService;

	@Autowired
	private ISplInfoService splInfoService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService ;

	@Autowired
	private ISplCommBlackListApiService splCommBlackListApiService ;

	@Autowired
	private ISplPropInfoApiService splPropInfoApiService;


	/**
	 * 到添加/修改页面
	 */
	@RequestMapping(value = "/toSplConfigPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("product/splInfo/splConfigAdd");
		this.prepare(request,view);
		return view;
	}

	/**
	 * 单独供应商配置维护页面
	 */
	@RequestMapping(value = "/toSingleConfigModifyPage.do", method = { RequestMethod.GET})
	public ModelAndView toSingleConfigModifyPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("product/splInfo/splConfigModify");
		//查询供应商基本信息
		String splId = request.getParameter("splId");
		SplInfoVO splVo = splInfoService.selectById(Long.valueOf(splId));
		SplUsrRQC splUsrRQC = new SplUsrRQC();
		splUsrRQC.setSplId(Long.valueOf(splId));
		splUsrRQC.setUsrTypCd(BaseConstant.IS_YESNO_YES_STR);//1 系统用户 2外部用户
		//splUsrRQC.setMgrFlag("1");//配置维护信息查询标识
		splUsrRQC.setSysCd(SplSystemConstant.FL_SYS_CD);
		List<SplUsrRVO> list = splUsrRService.searchList(splUsrRQC);
		List<Long> usrIds = new ArrayList<Long>();
		if(CollectionUtils.isNotEmpty(list)){
			for (SplUsrRVO splUsrRVO : list) {
				usrIds.add(splUsrRVO.getUsrId());
			}
		}
		view.addObject("isCheckCreditBlackList", 0);
		SplCommBlackListQC splCommBlackListQC = new SplCommBlackListQC();
		splCommBlackListQC.setIsDel(BaseConstant.IS_YESNO_NO);
		splCommBlackListQC.setIsValid(BaseConstant.IS_YESNO_YES);
		splCommBlackListQC.setUsrTypCd(BasisDataRelDescEnum.SPL.getTableSimpleNm());
		splCommBlackListQC.setBusTypCd(SplCommBlackListConstant.SHOP_APP_CHECKCREDIT_BLACK_LIST_BUS_TYP);
		splCommBlackListQC.setUsrId(Long.valueOf(splId));
		List<SplCommBlackListDTO> splCommBlackListDTOS = this.splCommBlackListApiService.searchSplCommBlackListDTOs(splCommBlackListQC);
		if(CollectionUtils.isNotEmpty(splCommBlackListDTOS)){
			view.addObject("isCheckCreditBlackList", 1);
		}

		view.addObject("isVip", 0);
		SplPropInfoQueryCondition splPropInfoQueryCondition = new SplPropInfoQueryCondition();
		splPropInfoQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
		splPropInfoQueryCondition.setIsValid(BaseConstant.IS_YESNO_YES);
		splPropInfoQueryCondition.setSplId(Long.valueOf(splId));
		splPropInfoQueryCondition.setPropTypCd("006");
		List<SplPropInfoDTO> splPropInfoDTOs = this.splPropInfoApiService.getSplPropInfoList(splPropInfoQueryCondition);
		if(null != splVo && !FlowConstant.FLOW_CHECK_STATE_NON.equals(splVo.getAudStsCd()) && !FlowConstant.FLOW_CHECK_STATE_IN.equals(splVo.getAudStsCd())
				&& !FlowConstant.FLOW_CHECK_STATE_NO_PASS.equals(splVo.getAudStsCd())  && !FlowConstant.FLOW_CHECK_STATE_REJECT.equals(splVo.getAudStsCd())
				&& CollectionUtils.isNotEmpty(splPropInfoDTOs) && StringUtils.isNotEmpty(splPropInfoDTOs.get(0).getPropInfo()) && splPropInfoDTOs.get(0).getPropInfo().contains("7")){
			view.addObject("isVip", 1);
		}

		view.addObject("usrIds", JSON.toJSON(usrIds));
		view.addObject("splVo",splVo);
		view.addObject("splNm", splVo.getSplNm());
		this.prepare(request,view);
		return view;
	}

	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toSplConfigDtail.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("product/splInfo/splConfigDetail");
		this.prepare(request,mav);
		return mav;
	}

	//加载数据字典数据、传值等 ？
	public void prepare(HttpServletRequest request,ModelAndView mav){
		//获取供应商业务类型下拉
		List<KeyValueVO> splBizTypCdList = splUsrRService.searchSplBizTypCdList();
		mav.addObject("splBizTypCdList", JSON.toJSON(splBizTypCdList));
		String splId = request.getParameter("splId");
		mav.addObject("splId", splId);

		//jiangzg add 2018-4-11 13:35:03 获取公海私海下拉
		List<KeyValueVO> isPrivateTypCdList = this.sysDictionaryApiService.getKvList(DictionaryConstant.SPL_IS_NOT_PRIVATE_SEA_CD, SplSystemConstant.SPL_SYS_CD,SplSystemConstant.DEFAULT_ORG_CD);
		mav.addObject("isPrivateTypCdList", JSON.toJSON(isPrivateTypCdList));

		//fengzuoxiang 2019-06-10  获取客户经理ID
		SplUsrRQC splUsrRQC = new SplUsrRQC();
		splUsrRQC.setSplId(Long.valueOf(splId));
		splUsrRQC.setUsrTypCd(BaseConstant.IS_YESNO_YES_STR);//1 系统用户 2外部用户
		splUsrRQC.setIsDel(BaseConstant.IS_YESNO_NO);
		splUsrRQC.setSysCd(SplSystemConstant.FL_SYS_CD);
		List<SplUsrRVO> list = splUsrRService.searchList(splUsrRQC);
		List<Long> usrIds = new ArrayList<Long>();
		if(CollectionUtils.isNotEmpty(list)){
			for (SplUsrRVO splUsrRVO : list) {
				usrIds.add(splUsrRVO.getUsrId());
			}
		}
		mav.addObject("usrIds", JSON.toJSON(usrIds));

	}
	/**
	 * 获取供应商配置列表
	 * zhaoyong
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/searchSplCofigInfo.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object searchSplCofigInfo (HttpServletRequest request, HttpServletResponse response){
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String splId = request.getParameter("splId");
		SplUsrRQC splUsrRQC = new SplUsrRQC();
		if(StringUtils.isEmpty(splId)){
			BaseLogUtils.newWebLogger("查询供应商配置列表,供应商id为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
			return "供应商id为空";
		}else{
			splUsrRQC.setSplId(Long.valueOf(splId));
			splUsrRQC.setUsrTypCd("1");//1 系统用户 2外部用户
			//splUsrRQC.setMgrFlag("1");//配置维护信息查询标识
			splUsrRQC.setSysCd(SplSystemConstant.FL_SYS_CD);
			try {
				Pager page = new Pager();
				if (StringUtils.isNotEmpty(currentPage)) {
					page.setCurrentPage(Integer.parseInt(currentPage));
				}

				if (StringUtils.isNotEmpty(pageSize)) {
					page.setEveryPage(Integer.parseInt(pageSize));
				}
				page.setCondition(splUsrRQC);
				page =  splUsrRService.searchListPage(page);
				List<SplUsrRVO> list =  (List<SplUsrRVO>) page.getResultList();
				ListPageVO<SplUsrRVO> listPage = new ListPageVO<SplUsrRVO>(list, page.getTotalCount());
				BaseLogUtils.newWebLogger("获取供应商配置列表数据.DATA:"+JSONObject.toJSONString(page)).setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.info();
				return listPage;
			}catch (BaseException ex) {
				BaseLogUtils.newWebLogger("获取供应商配置列表失败,业务异常").setLogOperType(LogOperEnum.REQ)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.setThrowable(ex)
						.warn(LogExceptionEnum.COMMON_CODE_0002);
			}catch (Exception ex) {
				BaseLogUtils.newWebLogger("获取供应商配置列表失败,系统异常").setLogOperType(LogOperEnum.REQ)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.setThrowable(ex)
						.error(LogExceptionEnum.COMMON_CODE_0099);
			}
		}
		return null;
	}

	/**
	 * 批量删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeSplUsrRByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if (StringUtils.isEmpty(ids)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.newWebLogger("删除SplUsrR数据,主键参数为空!").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
			return result;
		}

		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONObject.parseArray(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}

		try {
			boolean success = this.splUsrRService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.newWebLogger("删除SplUsrR数据失败,ID:"+idsList.toString()).setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.warn(LogExceptionEnum.COMMON_CODE_0002);

			}
			BaseLogUtils.newWebLogger("删除SplUsrR数据成功,ID:"+idsList.toString()).setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("删除SplUsrR数据失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("删除SplUsrR数据失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return result;
	}

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
    @ResponseBody
    public DataResultVO removeSplUsrRById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.newWebLogger("删除SplUsrR数据,主键参数为空!").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);

            return result;
        }
        try {
            boolean success = this.splUsrRService.removeById(Long.valueOf(id),CurrentThreadContext.getCurrentUserId());
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.newWebLogger("删除SplUsrR数据失败,ID:"+id).setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.warn(LogExceptionEnum.COMMON_CODE_0002);

            }
            BaseLogUtils.newWebLogger("删除SplUsrR数据成功,ID:"+id).setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();

        } catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("删除SplUsrR数据失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("删除SplUsrR数据失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
        return result;
    }

	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getSplUsrRById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.newWebLogger("获取SplUsrR数据,主键参数为空.").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
			return result;
		}

		try {
			SplUsrRVO vo = this.splUsrRService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.newWebLogger("获取SplUsrR数据不存在,ID:"+id)
						.setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.warn(LogExceptionEnum.COMMON_CODE_0002);

			}
			List<KeyValueVO> isPrivateCdList = this.sysDictionaryApiService.getKvList(DictionaryConstant.SPL_IS_NOT_PRIVATE_SEA_CD,SplSystemConstant.SPL_SYS_CD,SplSystemConstant.DEFAULT_ORG_CD);
			if(CollectionUtils.isNotEmpty(isPrivateCdList)){
				for(KeyValueVO keyValueVO : isPrivateCdList){
					if(null != vo && StringUtils.isNotEmpty(vo.getIsPrivate()) && keyValueVO.getKey().equals(vo.getIsPrivate())){
						vo.setIsPrivateCdNm(keyValueVO.getValue());
					}
				}
			}
			result.setData(vo);
			BaseLogUtils.newWebLogger("获取SplUsrR数据成功,ID:"+id)
					.setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("获取SplUsrR数据失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("获取SplUsrR数据失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return result;
	}

	/**
	 * 新增/修改
	 */
	@RequestMapping(value = "/addModify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addSplUsrR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		List<SplUsrRVO> list = null;//获取参数
		try {
			list = this.getRequestParamForSplUsrR(request);//获取参数
			if(CollectionUtils.isEmpty(list)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				return result ;
			}
			String buOrgCd = list.get(0).getBuOrgCd();// 客户经理所属事业部
			if (StringUtils.isEmpty(buOrgCd)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("系统错误,缺少事业部代码");
				BaseLogUtils.newWebLogger("客户经理所属事业部CODE为空").setLogOperType(LogOperEnum.REQ)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
						.setWarning(false)
						.warn(LogExceptionEnum.COMMON_CODE_0001);
				return result;
			}
			String splId = request.getParameter("splId");//供应商ID
			//String usrId = request.getParameter("usrId"); //用户ID
			if(StringUtils.isEmpty(splId)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				return result ;
			}
			/*List<SplUsrRVO> addSplUsrRList = new ArrayList<>(list.size());
			List<SplUsrRVO> mdfSplUsrRList = new ArrayList<>(list.size());
			*/
			/*for (SplUsrRVO splUsrRVO : list) {
				if(splUsrRVO.getId()==null){
					addSplUsrRList.add(splUsrRVO);
				}else{
					mdfSplUsrRList.add(splUsrRVO);
				}
				if(StringUtils.isNotEmpty(splUsrRVO.getIsPrivate())
						&& "1".equals(splUsrRVO.getIsPrivate())){
					isPrivateSize.add(splUsrRVO.getUsrId());
				}
			}*/
			List<Long> isPrivateSize = new ArrayList<>(list.size());
			for (SplUsrRVO splUsrRVO : list) {
				if(StringUtils.isNotEmpty(splUsrRVO.getIsPrivate())
						&& "1".equals(splUsrRVO.getIsPrivate())){
					isPrivateSize.add(splUsrRVO.getUsrId());
				}
			}
			// 校验该经销商是否只有一位客户经理是私海关系
			SplUsrRQC splUsrRQC = new SplUsrRQC();
			splUsrRQC.setSplId(Long.valueOf(splId));
			splUsrRQC.setIsDel(0);
			splUsrRQC.setIsPrivate("1");
			splUsrRQC.setBuOrgCd(buOrgCd);
			List<SplUsrRVO> splUsrRVOs = this.splUsrRService.searchList(splUsrRQC);
			if(CollectionUtils.isNotEmpty(splUsrRVOs)){
				for(SplUsrRVO vo : splUsrRVOs){
					if(CollectionUtils.isNotEmpty(isPrivateSize) && isPrivateSize.size() == 1){
						if(!isPrivateSize.contains(vo.getUsrId())){
							result.setSuccess(BaseConstant.IS_YESNO_NO);
							result.setInfo("私海客户经理有且仅有一个！请重新赋予私海权限！");
							isPrivateSize = null ;
							return result ;
						}
					}else{
						break;
					}
				}
			}

			if(CollectionUtils.isNotEmpty(isPrivateSize) && isPrivateSize.size() > 1){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("私海客户经理有且仅有一个！请重新赋予私海权限！");
				isPrivateSize = null ;
				return result ;
			}
			Long usrId = list.get(0).getUsrId();
			if(StringUtils.isEmpty(usrId)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_CURR_USER_NM_NOT_EMPTY);
				return result ;
			}
			SplUsrRQC qc = new SplUsrRQC();
			qc.setSplId(Long.valueOf(splId));
			qc.setUsrId(usrId);
			qc.setIsDel(9);
			qc.setBuOrgCd(buOrgCd);
			List<SplUsrRVO> splUsrRVOList = this.splUsrRService.searchList(qc);
			if(CollectionUtils.isNotEmpty(splUsrRVOList)){
				SplUsrRVO vo = splUsrRVOList.get(0);
				for(SplUsrRVO splUsrRVO : list){
					if(splUsrRVO.getSplId().equals(vo.getSplId()) &&
							splUsrRVO.getUsrId().equals(vo.getUsrId())){
						vo.setBuOrgCd(splUsrRVO.getBuOrgCd());
						vo.setEffectDt(new Date());
						vo.setIsChg(splUsrRVO.getIsChg());
						vo.setIsDel(splUsrRVO.getIsDel());
						vo.setIsPrivate(splUsrRVO.getIsPrivate());
						vo.setIsSysDef(splUsrRVO.getIsSysDef());
						vo.setIsValidForever(splUsrRVO.getIsValidForever());
						vo.setOrgCd(splUsrRVO.getOrgCd());
						vo.setSplBizTypCd(splUsrRVO.getSplBizTypCd());
						vo.setCrtTm(new Date());
						vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
						vo.setUsrTypCd(StringUtils.isNotEmpty(splUsrRVO.getUsrTypCd()) ? splUsrRVO.getUsrTypCd() : "1");
						this.splUsrRService.modify(vo);
					}
				}
			}else{
				for (SplUsrRVO splUsrRVO : list) {
					this.splUsrRService.add(splUsrRVO);
				}
			}
			BaseLogUtils.newWebLogger("保存SplUsrR数据成功.DATA:"+JSONObject.toJSONString(list))
					.setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
			//增加判断，保存开关配置信息
			//SplInfoVO vo = new SplInfoVO();
			//String splId = request.getParameter("splId");
			//String isAuthCrdChk = request.getParameter("isAuthCrdChk");

			//String livSwitch = request.getParameter("livSwitch");//前置征信活体开关
			//String crdLoaSwitch = request.getParameter("crdLoaSwitch");//前置征信授权书开关
			//boolean success = true;
			//if(StringUtils.isNotEmpty(isAuthCrdChk)){
			//	vo.setIsAuthCrdChk(Integer.valueOf(isAuthCrdChk));

			//	vo.setLivSwitch(Integer.valueOf(livSwitch));//前置征信活体开关
			//	vo.setCrdLoaSwitch(Integer.valueOf(crdLoaSwitch));//前置征信授权书开关

			//	String limChkTms = request.getParameter("limChkTms");
			//	vo.setLimChkTms(Integer.valueOf(limChkTms));
			//	vo.setId(Long.valueOf(splId));
			//	success = this.splInfoService.modifySplInfo(vo);
			//	BaseLogUtils.info(logger, "addModifySplUsrR", "保存征信开关数据::"+success+".DATA:"+JSONObject.toJSONString(vo), CurrentThreadContext.getCurrentUserName());
			//}
			//result.setData(success);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.newWebLogger("保存SplUsrR数据失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.newWebLogger("保存SplUsrR数据失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return result;
	}

    /**
     * 新增或修改供应商客户关系（校验事业部 私海规则）
     */
    @RequestMapping(value = "/addOrModifySplUsrR.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object addOrModifySplUsrR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		List<SplUsrRVO> list = null;
        try {
			list = this.getRequestParamForSplUsrR(request);//获取参数
			if(CollectionUtils.isEmpty(list)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				return result ;
			}
			SplUsrRVO splUsrRVO = list.get(0);
			String buOrgCd = splUsrRVO.getBuOrgCd();// 客户经理所属事业部

			if(!buOrgCd.equals(SplBscInfoApplyConstant.SPL_ADMISSION_ORG_CD_14)){
				if(splUsrRVO.getSplBizTypCd().contains("lcv")){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("该事业部不支持LCV业务类型!");
					return result ;
				}
			}

            if(StringUtils.isEmpty(splUsrRVO.getId())){
				if(buOrgCd.equals(SplBscInfoApplyConstant.SPL_ADMISSION_ORG_CD_14)){
					SplUsrRQC qc = new SplUsrRQC();
					qc.setSplId(splUsrRVO.getSplId());
					qc.setBuOrgCd(buOrgCd);
					qc.setUsrTypCd(BaseConstant.IS_YESNO_YES_STR);
					List<SplUsrRVO> splUsrRVOS = this.splUsrRService.searchList(qc);
					if(CollectionUtils.isNotEmpty(splUsrRVOS)){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("该事业部只能维护一个客户关系!");
						return result ;
					}
				}
				SplUsrRQC splUsrRQC = new SplUsrRQC();
				splUsrRQC.setSplId(splUsrRVO.getSplId());
				splUsrRQC.setUsrId(splUsrRVO.getUsrId());
				splUsrRQC.setIsDel(9);
                List<SplUsrRVO> splUsrRVOList = this.splUsrRService.searchList(splUsrRQC);
                if(CollectionUtils.isEmpty(splUsrRVOList)){
                    this.splUsrRService.add(splUsrRVO);
                }else{
                    SplUsrRVO usrRVO = splUsrRVOList.get(0);
                    usrRVO.setBuOrgCd(splUsrRVO.getBuOrgCd());
                    usrRVO.setEffectDt(splUsrRVO.getEffectDt());
                    usrRVO.setIsChg(splUsrRVO.getIsChg());
                    usrRVO.setIsDel(splUsrRVO.getIsDel());
                    usrRVO.setIsPrivate(splUsrRVO.getIsPrivate());
                    usrRVO.setIsSysDef(splUsrRVO.getIsSysDef());
                    usrRVO.setEmployeePosCd(splUsrRVO.getEmployeePosCd());
                    usrRVO.setIsValidForever(splUsrRVO.getIsValidForever());
                    usrRVO.setOrgCd(splUsrRVO.getOrgCd());
                    usrRVO.setSplBizTypCd(splUsrRVO.getSplBizTypCd());
                    usrRVO.setSplId(splUsrRVO.getSplId());
                    usrRVO.setUsrId(splUsrRVO.getUsrId());
                    usrRVO.setUsrTypCd(splUsrRVO.getUsrTypCd());
                    usrRVO.setCrtTm(splUsrRVO.getCrtTm());
                    usrRVO.setCrtUsrId(splUsrRVO.getCrtUsrId());
                    this.splUsrRService.modify(usrRVO);
                }

            }else{
                this.splUsrRService.modify(splUsrRVO);
            }
            BaseLogUtils.newWebLogger("保存SplUsrR数据成功.DATA:"+JSONObject.toJSONString(list))
					.setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.info();
        }catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("保存SplUsrR数据失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.newWebLogger("保存SplUsrR数据失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
        return result;
    }

	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return
	 */
	private List<SplUsrRVO> getRequestParamForSplUsrR(HttpServletRequest request) throws BaseException{
		//获取参数
		String splId = request.getParameter("splId");//供应商ID
        if(StringUtils.isEmpty(splId)){
            throw new BaseException(BaseExceptionConstant.COMMON_0001, "供应商ID不能为空.");
        }
		JSONArray mgrList = JSONObject.parseArray(request.getParameter("mgrListJSON"));//管理员信息
		List<SplUsrRVO> splUsrRlist = new ArrayList<SplUsrRVO>();
		Date date = new Date();
		if(CollectionUtils.isNotEmpty(mgrList)){//事业部不为空
			for (int i = 0; i < mgrList.size(); i++) {
				SplUsrRVO usrRVo = new SplUsrRVO();
				JSONObject orgJo = (JSONObject) mgrList.get(i);
				String splBizTypCd = orgJo.getString("splBizTypCd");
                if (StringUtils.isEmpty(splBizTypCd)) {
                    throw new BaseException(BaseExceptionConstant.COMMON_0001, "供应商业务类型不能为空.");
                }
				String usrId = orgJo.getString("usrId");
                if (StringUtils.isEmpty(usrId)) {
                    throw new BaseException(BaseExceptionConstant.COMMON_0001, "未选择管理员，请删除行重新添加.");
                }
                String buOrgCd = orgJo.getString("buOrgCd");
                if (StringUtils.isEmpty(buOrgCd) || buOrgCd.length()< 8 ) {
                    throw new BaseException(BaseExceptionConstant.COMMON_0001, "客户经理所属事业部CODE不能为空.");
                }
				String id = orgJo.getString("id");// 供应商-系统用户关系表主键ID
                if(StringUtils.isNotBlank(orgJo.getString("id"))){
                    usrRVo.setId(Long.valueOf(id));
                }
				String orgCd = "";
				if (StringUtils.isEmpty(id)) {
					orgCd = buOrgCd;//客户经理所属事业部
				} else {
					orgCd = orgJo.getString("orgCd");
				}
				usrRVo.setSplBizTypCd(splBizTypCd);
				usrRVo.setUsrId(Long.valueOf(usrId));
				usrRVo.setSplId(Long.valueOf(splId));

				usrRVo.setIsChg(BaseConstant.IS_YESNO_NO);//非主管
				usrRVo.setIsSysDef(BaseConstant.IS_YESNO_NO);//非系统内置
				usrRVo.setCrtTm(date);
				usrRVo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				usrRVo.setUsrTypCd(BaseConstant.IS_YESNO_YES_STR);//内部用户

				usrRVo.setBuOrgCd(buOrgCd.substring(0,8));//客户经理所属事业部
				usrRVo.setOrgCd(orgCd);//客户经理所属组织架构

				if(StringUtils.isNotEmpty(orgJo.getString("isPrivate")) && BaseConstant.IS_YESNO_YES_STR.equalsIgnoreCase(orgJo.getString("isPrivate"))){
					usrRVo.setIsPrivate(BaseConstant.IS_YESNO_YES_STR);
                    usrRVo.setIsValidForever(BaseConstant.IS_YESNO_YES_STR);
				}else{
					usrRVo.setIsPrivate(BaseConstant.IS_YESNO_NO_STR);
                    usrRVo.setIsValidForever(BaseConstant.IS_YESNO_NO_STR);
				}
                usrRVo.setEffectDt(date);
				usrRVo.setIsDel(BaseConstant.IS_YESNO_NO);
				splUsrRlist.add(usrRVo);
			}
		}
		return splUsrRlist;
	}
}